package com.edu.unit06;

import java.time.Duration;
import java.time.Instant;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * 时间线
 *
 * @作者 five-five
 * @创建时间 2021/4/13
 */
public class Demo01 {
    public static void main(String[] args) throws Exception {
        //Instant:时间线上的瞬时点。此类在时间轴上为单个瞬时点建模。 这可用于记录应用程序中的事件时间戳。
        Instant start = Instant.now();
        Thread.sleep(1000);
        Instant end = Instant.now();
        Duration timeElapsed = Duration.between(start, end);
        System.out.println(timeElapsed.toNanos());//纳秒
        System.out.println(timeElapsed.toMillis());//毫秒
        System.out.println(timeElapsed.getSeconds());//秒
        System.out.println(timeElapsed.toMinutes());//分
        System.out.println(timeElapsed.toHours());//小时
        System.out.println(timeElapsed.toDays());//天
        //Instant可记录的最大值
        System.out.println(Instant.MAX);

        //测试从书上敲得代码
        Demo01 demo01 = new Demo01();
        demo01.codeWithBook();
    }

    /**
     * 书上的代码(手敲过一遍)
     */
    public void codeWithBook() {
        Instant start = Instant.now();
        runAlgorithm1();
        Instant end = Instant.now();
        Duration timeElapsed = Duration.between(start, end);
        long millis = timeElapsed.toMillis();
        System.out.printf("%d millissecods\n", millis);

        Instant start2 = Instant.now();
        runAlgorithm2();
        Instant end2 = Instant.now();
        Duration timeElapsed2 = Duration.between(start2, end2);
        long millis2 = timeElapsed2.toMillis();
        System.out.printf("%d millissecods\n", millis2);

        boolean overTenTimesFaster = timeElapsed.multipliedBy(5)
                .minus(timeElapsed2).isNegative();
        System.out.println(overTenTimesFaster);
    }

    /**
     * 一个简单的函数
     */
    private void runAlgorithm1() {
        int size = 10;
        List<Integer> list = new Random().ints().map(i -> i % 100).limit(size).
                boxed().collect(Collectors.toList());
        Collections.sort(list);
        System.out.println(list);
    }

    /**
     * 一个简单的函数
     */
    private void runAlgorithm2() {
        int size = 10;
        List<Integer> list = new Random().ints().map(i -> i % 100).limit(size).
                boxed().collect(Collectors.toList());
        while (!IntStream.range(1, list.size())
                .allMatch(i -> list.get(i).compareTo(list.get(i)) <= 0)) {
            Collections.shuffle(list);
            System.out.println(list);
        }
    }
}
